package com.mapperdb.mapping;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.UnknownTypeHandler;

/**
 * Result 注解 映射类
 * @author Administrator
 *
 */
public class Result {
	boolean before = true;

	boolean id = false;

	String column = "";

	String property = "";

	Class<?> javaType;

	JdbcType jdbcType;

	Class<? extends TypeHandler<?>> typeHandler;

	public boolean isBefore() {
		return before;
	}

	public boolean isId() {
		return id;
	}

	public String getColumn() {
		return column;
	}

	public String getProperty() {
		return property;
	}

	public Class<?> getJavaType() {
		return javaType;
	}

	public JdbcType getJdbcType() {
		return jdbcType;
	}

	public Class<? extends TypeHandler<?>> getTypeHandler() {
		return typeHandler;
	}

	public String formatEqualsColumn() {
		StringBuffer sb = new StringBuffer();
		sb.append(column).append(" = ");
		sb.append("#{").append(property);
		if (javaType != null) sb.append(",javaType=").append(javaType.getName());
		if (jdbcType != null) sb.append(",jdbcType=").append(jdbcType.name());
		if (typeHandler != null) sb.append(",typeHandler=").append(typeHandler.getName());
		sb.append("}");
		return sb.toString();
	}

	public String format() {
		StringBuffer sb = new StringBuffer();
		sb.append("#{").append(property);
		if (javaType != null) sb.append(",javaType=").append(javaType.getName());
		if (jdbcType != null) sb.append(",jdbcType=").append(jdbcType.name());
		if (typeHandler != null) sb.append(",typeHandler=").append(typeHandler.getName());
		sb.append("}");
		return sb.toString();
	}

	/*-------------------------------- Builder ----------------------------------*/
	public static Builder use() {
		return new Builder();
	}

	public static class Builder {
		Result p = new Result();

		protected Builder() {
		}

		public Builder id(boolean id) {
			p.id = id;
			return this;
		}

		public Builder before(boolean before) {
			p.before = before;
			return this;
		}

		public Builder column(String column) {
			p.column = column;
			return this;
		}

		public Builder property(String property) {
			p.property = property;
			return this;
		}

		public Builder javaType(Class<?> javaType) {
			p.javaType = javaType;
			return this;
		}

		public Builder jdbcType(JdbcType jdbcType) {
			p.jdbcType = jdbcType;
			return this;
		}

		public Builder typeHandler(Class<? extends TypeHandler<?>> typeHandler) {
			p.typeHandler = typeHandler;
			return this;
		}

		public Result build() {
			if (p.javaType == Void.TYPE) p.javaType = null;
			if (p.jdbcType == JdbcType.UNDEFINED) p.jdbcType = null;
			if (p.typeHandler == UnknownTypeHandler.class) p.typeHandler = null;
			if (!p.id) p.before = true;

			return p;
		}
	}
}
